using System;
using System.Threading;
using System.Threading.Tasks;
using RTMP.SimpleClient;
using RTMP.SimpleClient.Tests.MockServer;

namespace RTMP.SimpleClient.Tests.MockServer
{
    /// <summary>
    /// Mock RTMP 服务器使用示例
    /// </summary>
    public class MockServerExample
    {
        /// <summary>
        /// 运行Mock服务器示例
        /// </summary>
        public static async Task RunExample()
        {
            Console.WriteLine("=== RTMP Mock服务器使用示例 ===\n");

            // 1. 创建Mock服务器
            using var mockServer = new RTMPMockServer();
            
            // 2. 设置事件处理器
            mockServer.StateChanged += (sender, e) =>
            {
                Console.WriteLine($"[事件] 服务器状态变化: {e.PreviousState} -> {e.NewState}");
            };

            mockServer.ClientConnected += (sender, e) =>
            {
                Console.WriteLine($"[事件] 客户端连接: {e.ClientEndpoint}");
            };

            mockServer.ClientDisconnected += (sender, e) =>
            {
                Console.WriteLine($"[事件] 客户端断开: {e.ClientEndpoint} (原因: {e.Reason ?? "未知"})");
            };

            mockServer.CommandReceived += (sender, e) =>
            {
                Console.WriteLine($"[事件] 收到RTMP命令: {e.CommandName} (事务ID: {e.TransactionId})");
            };

            try
            {
                // 3. 启动Mock服务器
                Console.WriteLine("启动Mock RTMP服务器...");
                await mockServer.StartAsync("127.0.0.1", 0); // 0表示自动选择端口
                
                Console.WriteLine($"Mock服务器启动成功，监听地址: {mockServer.Host}:{mockServer.Port}");
                Console.WriteLine($"服务器状态: {mockServer.CurrentState}");

                // 4. 创建RTMP客户端并连接到Mock服务器
                var serverUrl = $"rtmp://{mockServer.Host}:{mockServer.Port}/live";
                Console.WriteLine($"\n使用RTMP客户端连接到Mock服务器: {serverUrl}");

                using var client = new RTMPSimpleClient();
                
                // 连接到服务器
                Console.WriteLine("正在连接...");
                await client.ConnectAsync(serverUrl, cancellationToken: CancellationToken.None);
                Console.WriteLine("✓ 连接成功");

                // 等待一段时间让握手完成
                await Task.Delay(1000);
                Console.WriteLine($"服务器状态: {mockServer.CurrentState}");

                // 创建流
                Console.WriteLine("\n创建RTMP流...");
                var streamId = await client.CreateStreamAsync();
                Console.WriteLine($"✓ 创建流成功，流ID: {streamId}");

                // 播放流
                Console.WriteLine("\n开始播放流...");
                await client.PlayAsync(streamId, "test_stream");
                Console.WriteLine("✓ 开始播放");

                // 等待一段时间让状态稳定
                await Task.Delay(2000);
                Console.WriteLine($"最终服务器状态: {mockServer.CurrentState}");

                // 关闭客户端连接
                Console.WriteLine("\n关闭客户端连接...");
                await client.CloseAsync();
                Console.WriteLine("✓ 客户端连接已关闭");

                // 等待服务器清理
                await Task.Delay(1000);
                Console.WriteLine($"服务器状态: {mockServer.CurrentState}");

            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 示例运行失败: {ex.Message}");
                Console.WriteLine($"详细信息: {ex}");
            }
            finally
            {
                // 5. 停止Mock服务器
                Console.WriteLine("\n停止Mock服务器...");
                await mockServer.StopAsync();
                Console.WriteLine("✓ Mock服务器已停止");
                Console.WriteLine($"最终状态: {mockServer.CurrentState}");
            }

            Console.WriteLine("\n=== 示例结束 ===");
        }

        /// <summary>
        /// 展示Mock服务器的状态机功能
        /// </summary>
        public static async Task DemonstrateStateMachine()
        {
            Console.WriteLine("=== RTMP Mock服务器状态机演示 ===\n");

            using var mockServer = new RTMPMockServer();
            var stateHistory = new System.Collections.Generic.List<MockServerState>();

            // 记录状态变化历史
            mockServer.StateChanged += (sender, e) =>
            {
                stateHistory.Add(e.NewState);
                Console.WriteLine($"状态转换: {e.PreviousState} -> {e.NewState} (时间: {e.Timestamp:HH:mm:ss.fff})");
            };

            try
            {
                Console.WriteLine("初始状态: " + mockServer.CurrentState);

                // 启动服务器
                await mockServer.StartAsync("127.0.0.1", 0);
                await Task.Delay(500);

                // 连接客户端
                using var client = new RTMPSimpleClient();
                var serverUrl = $"rtmp://{mockServer.Host}:{mockServer.Port}/live";
                
                await client.ConnectAsync(serverUrl);
                await Task.Delay(1000);

                var streamId = await client.CreateStreamAsync();
                await Task.Delay(500);

                await client.PlayAsync(streamId, "demo_stream");
                await Task.Delay(1000);

                await client.CloseAsync();
                await Task.Delay(500);

                Console.WriteLine("\n状态转换历史:");
                Console.WriteLine("Stopped -> " + string.Join(" -> ", stateHistory));

            }
            catch (Exception ex)
            {
                Console.WriteLine($"状态机演示失败: {ex.Message}");
            }
            finally
            {
                await mockServer.StopAsync();
            }
        }

        /// <summary>
        /// 演示Mock服务器的命令处理能力
        /// </summary>
        public static async Task DemonstrateCommandProcessing()
        {
            Console.WriteLine("=== RTMP Mock服务器命令处理演示 ===\n");

            using var mockServer = new RTMPMockServer();
            var commandHistory = new System.Collections.Generic.List<string>();

            // 记录收到的命令
            mockServer.CommandReceived += (sender, e) =>
            {
                commandHistory.Add($"{e.CommandName}(TID:{e.TransactionId})");
                Console.WriteLine($"收到命令: {e.CommandName}, 事务ID: {e.TransactionId}, 时间: {e.Timestamp:HH:mm:ss.fff}");
            };

            try
            {
                await mockServer.StartAsync("127.0.0.1", 0);
                Console.WriteLine($"Mock服务器启动，地址: {mockServer.Host}:{mockServer.Port}");

                using var client = new RTMPSimpleClient();
                var serverUrl = $"rtmp://{mockServer.Host}:{mockServer.Port}/live";

                // 执行一系列RTMP操作
                await client.ConnectAsync(serverUrl);
                await Task.Delay(500);

                var streamId1 = await client.CreateStreamAsync();
                await Task.Delay(300);

                var streamId2 = await client.CreateStreamAsync();
                await Task.Delay(300);

                await client.PlayAsync(streamId1, "stream_1");
                await Task.Delay(300);

                await client.PlayAsync(streamId2, "stream_2");
                await Task.Delay(500);

                Console.WriteLine($"\n总共处理的命令: {commandHistory.Count}");
                Console.WriteLine("命令序列: " + string.Join(" -> ", commandHistory));

                await client.CloseAsync();

            }
            catch (Exception ex)
            {
                Console.WriteLine($"命令处理演示失败: {ex.Message}");
            }
            finally
            {
                await mockServer.StopAsync();
            }
        }
    }
}